package com.wltjack.springboot.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wltjack.springboot.dao.UserDao;
import com.wltjack.springboot.service.EsUserService;
import com.wltjack.springboot.vo.esEntity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class EsUserServiceImpl implements EsUserService {
    @Autowired
    private UserDao userDao;

    @Override
    public UserEntity addUser(UserEntity userEntity) {
        UserEntity userEntity1 = userDao.save(userEntity);
        return userEntity1;
    }

    @Override
    public Optional<UserEntity> findById(String id) {
        return userDao.findById(id);
    }

    @Override
    public String search(String keyWord) {
        List<UserEntity> resultList = new ArrayList<UserEntity>();

        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.matchQuery("name",keyWord).operator(Operator.AND));
        Iterable<UserEntity> searchResult = userDao.search(queryBuilder);

//        QueryBuilder queryBuilder = QueryBuilders.matchQuery("name",keyWord).operator(Operator.AND);
//        Iterable<UserEntity> searchResult = userDao.search(queryBuilder);

        Iterator<UserEntity> iterator = searchResult.iterator();
        while(iterator.hasNext()){
            UserEntity item = iterator.next();
            resultList.add(item);
        }
        //生成DSL查询语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(queryBuilder);
        log.info("EsUserServiceImpl - search() query sql -> " + sourceBuilder.toString());
        return JSONObject.toJSONString(resultList);
    }
}
